import React, { useEffect } from 'react';
import { StyleSheet, Text } from 'react-native';
import {
  Badge,
  Button,
  Flex,
  List,
  Picker,
  Tabs,
  Toast,
  WingBlank,
} from '@ant-design/react-native';
import FlexTextField from '@/rcomponents/flexTextField';
import { LoadingContainer } from '@/rcomponents/Container';
import { formatDate } from '@/helpers/dateutil';
import UserStore from '@/stores/userStore';
import Card from './components/responsiveCard';
import ReleaseJobStore from './releaseJobStore';

const styles = StyleSheet.create({
  fatherContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    flexWrap: 'wrap',
    fontWeight: 'bold',
    width: 300,
    lineHeight: 30,
  },
});

const ScAreaList = [
  {
    title: '货仓',
  },
  {
    title: '机身',
  },
  {
    title: '发动机',
  },
  {
    title: '客舱',
  },
  {
    title: '电气电子',
  },
  {
    title: '其他',
  },
];
function ScReleaseJobPage({ navigation, route }) {
  const rjStore = ReleaseJobStore.useStore();
  const userStore = UserStore.useStore();
  useEffect(() => {
    handleLoadJob();
  }, [route.params]);
  const handleLoadJob = async () => {
    if (route.params) {
      await Promise.all([
        rjStore.getScPassJobDetail(
          userStore.user.LoginName,
          route.params.taskStageTid,
          route.params.flightTid,
        ),
        rjStore.getPassInfo(
          userStore.user.LoginName,
          route.params.taskStageTid,
        ),
      ]);
    }
  };
  const handleTaskReturn = (item) => {
    navigation.navigate(JobReturnPage.routeName, {
      taskTid: item.id,
      taskStageTid: route.params.taskStageTid,
      flightTid: route.params.flightTid,
    });
  };
  const handleAreaDesignate = async (job, oldArea, areaPicker) => {
    const oldAreaIdx = ScAreaList.findIndex((scc) => scc.title === oldArea);
    const newAreaIdx = ScAreaList.findIndex((scc) => scc.title === areaPicker);
    const res = await rjStore.designateJobArea(
      userStore.user.LoginName,
      job.id,
      areaPicker,
      oldAreaIdx,
      newAreaIdx,
    );
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
    }
  };
  const renderScChild = (tab, index) => {
    const scChildData = rjStore.scPassDetail[index] || [];
    return (
      <LoadingContainer
        onRefresh={handleLoadJob}
        loading={rjStore.getScPassJobDetail.loading}
        data={scChildData}
        renderItem={({ item }) => (
          <Card key={item.id}>
            <Card.Header
              title={
                <Flex style={styles.fatherContainer} numberOfLines={10}>
                  <Text style={styles.pwCardTitle}>
                    {item.cardTitle.replace(/<\/?.+?\/?>/g, '\n')}
                  </Text>
                </Flex>
              }
            />
            <Card.Body>
              <Flex>
                <FlexTextField label="工卡号" fieldValue={item.jobCard} />
              </Flex>
              <Flex>
                <FlexTextField label="指令号" fieldValue={item.workOrder} />
                <FlexTextField label="工作者" fieldValue={item.workPer} />
              </Flex>
              <Flex>
                <FlexTextField
                  label="计划"
                  fieldValue={formatDate(item.planDate, 'YYYY-MM-DD HH:mm')}
                />
                <FlexTextField
                  label="完工"
                  fieldValue={formatDate(item.finishDate, 'YYYY-MM-DD HH:mm')}
                />
              </Flex>
              <Flex>
                <FlexTextField label="状态" fieldValue={item.planStatusDes} />
              </Flex>
            </Card.Body>
            <Card.Footer
              extra={
                <Flex>
                  {item.planStatus !== '11' && item.planStatus !== '13' && (
                    <WingBlank>
                      <Button
                        type="ghost"
                        size="small"
                        onPress={() => handleTaskReturn(item)}
                      >
                        退单
                      </Button>
                    </WingBlank>
                  )}
                  {item.planStatus !== '11' &&
                    item.planStatus !== '7' &&
                    item.planStatus !== '13' && (
                      <Picker
                        data={ScAreaList.map((scd) => ({
                          value: scd.title,
                          label: scd.title,
                        }))}
                        cols={1}
                        value={tab.title}
                        onOk={(val) =>
                          handleAreaDesignate(item, tab.title, val[0])
                        }
                      >
                        <Button
                          type="primary"
                          size="small"
                          loading={rjStore.designateJobArea.loading}
                        >
                          区域指派
                        </Button>
                      </Picker>
                    )}
                </Flex>
              }
            />
          </Card>
        )}
      />
    );
  };
  const passPara = {
    taskStageTid: route.params.taskStageTid,
    flightTid: route.params.flightTid,
    taskType: 'SC',
  };
  const handleJobPass = async () => {
    const paraVerify = await rjStore.verifyPass(
      userStore.user.LoginName,
      route.params.taskStageTid,
      route.params.flightTid,
    );
    if (paraVerify.data !== true) {
      Toast.fail(paraVerify.errorMsg);
      return;
    }
    const res = await rjStore.passTask(userStore.user.LoginName, passPara);
    if (res.errorCode) {
      Toast.fail({ content: res.errorMsg });
      return;
    }
    navigation.goBack();
  };
  return (
    <>
      <Tabs
        tabs={ScAreaList.map((scc, index) => ({
          title: (
            <Badge
              text={(rjStore.scPassDetail[index] || []).length}
              key={scc.title}
            >
              <Text>{scc.title}</Text>
            </Badge>
          ),
        }))}
      >
        {renderScChild}
      </Tabs>
      {!rjStore.scPassInfo && (
        <Button
          type="primary"
          onPress={handleJobPass}
          loading={rjStore.passTask.loading}
        >
          放行确认
        </Button>
      )}
      {rjStore.scPassInfo && (
        <List renderHeader="放行信息">
          <List.Item extra={rjStore.scPassInfo.Name}>放行人员</List.Item>
          <List.Item
            extra={formatDate(rjStore.scPassInfo.date, 'YYYY-MM-DD HH:mm:ss')}
          >
            放行时间
          </List.Item>
          <List.Item extra="">已放行</List.Item>
        </List>
      )}
    </>
  );
}

ScReleaseJobPage.routeName = 'ScReleaseJob';
ScReleaseJobPage.permission = 'RScReleaseJob';
export default ScReleaseJobPage;
